/*
 * @lc app=leetcode.cn id=1122 lang=javascript
 *
 * [1122] 数组的相对排序
 */

// @lc code=start
/**
 * @param {number[]} arr1
 * @param {number[]} arr2
 * @return {number[]}
 */
var relativeSortArray = function(arr1, arr2) {
    let map=new Map()
    let res_head=[]
    let res_fail=[]
    for(let i=0;i<arr1.length;i++){
        if(map.has(arr1[i])){
            map.set(arr1[i],map.get(arr1[i])+1)
        }else{
            map.set(arr1[i],1)
        }
    }
    for(let i=0;i<arr1.length;i++){
        while(map.get(arr2[i])){
            res_head.push(arr2[i])
            map.set(arr2[i],map.get(arr2[i])-1)
        }
    }
    map.forEach((v,k)=>{
        while(v){
            v--
            res_fail.push(k)
        }
    })
    return res_head.concat(res_fail.sort((a,b)=>a-b))
};//可以使用变种sort
// @lc code=end

var relativeSortArray = function(arr1, arr2) {
    return arr1.sort((a, b) => {
        let ia = arr2.indexOf(a);
        let ib = arr2.indexOf(b);
        if(ia == -1 && ib == -1) {
            return a - b;
        } else if (ia == -1) {
            return 1;
        } else if (ib == -1) {
            return -1;
        } else {
            return ia-ib;
        }
    });
};
